<!-- NotificationDrawer.vue -->
<template>
  <el-drawer
      title="通知列表"
      size="320px"
      direction="rtl"
      :with-header="true"
      v-model="drawer"
      @close="closeDrawer"
      custom-class="custom-drawer"
  >
    <template #header="{ close, titleId, titleClass }">
      <h4 :id="titleId" :class="titleClass">通知列表</h4>
      <div class="button">
        <el-button type="text" size="default" @click="readMessage">一键已读</el-button>
      </div>
    </template>
    <el-tabs style="width: 100%" v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="全部" name="all">
        <div v-for="item in filteredObj" :key="item.messageId" class="notification-item">
          <el-badge :hidden="item.readStatus === 1" is-dot class="item">
            <span class="msgTitle" @click="clickMsg(item)">
              {{ item.title }}
            </span>
          </el-badge>
          <span class="msgTime">{{ item.time }}</span>
          <div v-if="item.title === '订单变更申请'" class="msgContent">
            {{ safeJsonParse(item.content).content}}
          </div>

          <div v-if="item.title === '商品修改通知'" class="msgContent">
            {{ safeJsonParse(item.content).changes }}
          </div>

          <div v-if="item.title === '订单确认通知'" class="msgContent">
            {{ safeJsonParse(item.content).content }}
          </div>

          <div v-else v-for="(change, index) in safeJsonParse(item.content).changes"
               class="msgContent"
               :key="index"
               v-if="Array.isArray(safeJsonParse(item.content).changes)">
            {{ change.description }}
          </div>
          <div class="action-button">
            <el-button type="text" @click="viewDetails(item)" size="small">查看详情</el-button>
          </div>
          <el-divider></el-divider>
        </div>
      </el-tab-pane>
      <el-tab-pane label="已读" name="1">
        <div v-for="item in filteredObj" :key="item.messageId" class="notification-item">
          <el-badge :hidden="item.readStatus === 1" is-dot class="item">
            <span class="msgTitle" @click="clickMsg(item)">
              {{ item.title }}
            </span>
          </el-badge>
          <span class="msgTime">{{ item.time }}</span>
          <div v-if="item.title === '订单变更申请'" class="msgContent">
            {{ safeJsonParse(item.content).content}}
          </div>

          <div v-if="item.title === '商品修改通知'" class="msgContent">
            {{ safeJsonParse(item.content).changes }}
          </div>

          <div v-if="item.title === '订单确认通知'" class="msgContent">
            {{ safeJsonParse(item.content).content }}
          </div>

          <div v-else v-for="(change, index) in safeJsonParse(item.content).changes"
               class="msgContent"
               :key="index"
               v-if="Array.isArray(safeJsonParse(item.content).changes)">
            {{ change.content }}
          </div>
          <div class="action-button">
            <el-button type="text" @click="viewDetails(item)" size="small">查看详情</el-button>
          </div>
          <el-divider></el-divider>
        </div>
      </el-tab-pane>
      <el-tab-pane label="未读" name="0">
        <div v-for="item in filteredObj" :key="item.messageId" class="notification-item">
          <el-badge :hidden="item.readStatus === 1" is-dot class="item">
            <span class="msgTitle" @click="clickMsg(item)">
              {{ item.title }}
            </span>
          </el-badge>
          <span class="msgTime">{{ item.time }}</span>
          <div v-if="item.title === '订单变更申请'" class="msgContent">
            {{ safeJsonParse(item.content).content }}
          </div>

          <div v-if="item.title === '商品修改通知'" class="msgContent">
            {{ safeJsonParse(item.content).changes }}
          </div>

          <div v-if="item.title === '订单确认通知'" class="msgContent">
            {{ safeJsonParse(item.content).content }}
          </div>

          <div v-else v-for="(change, index) in safeJsonParse(item.content).changes"
               class="msgContent"
               :key="index"
               v-if="Array.isArray(safeJsonParse(item.content).changes)">
            {{ change.description }}
          </div>
          <div class="action-button">
            <el-button type="text" @click="viewDetails(item)" size="small">查看详情</el-button>
          </div>
          <el-divider></el-divider>
        </div>
      </el-tab-pane>
    </el-tabs>
    <el-pagination
        v-show="messagetotal > 0"
        :current-page="page.pageNum"
        :page-size="page.pageSize"
        :page-sizes="[5, 10, 20]"
        :total="messagetotal"
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
        :pager-count="5"
        small
    />
  </el-drawer>
</template>

<script>import { ref, computed, onMounted } from 'vue';
import { useDrawerStore } from "@/store/drawerStore.js";
import {listMessage, getMessage, getMessageByName, updateMessage} from "@/api/system/message.js";
import {useRouter} from 'vue-router'


export default {

  props:{
    userId:{
      type: Number,
      required: true,
      default: 2
    }
  },

  setup(props) {
    const router = useRouter();
    const drawerStore = useDrawerStore();
    const drawer = computed(() => drawerStore.drawer);
    const obj = ref([]);
    const activeName = ref('all');
    const filteredObj = computed(() => {
      if (activeName.value === 'all') {
        return obj.value;
      } else {
        return obj.value.filter(item => item.readStatus === parseInt(activeName.value));
      }
    });
    const total = ref(0);
    const messagetotal = ref(0);
    const page = ref({
      pageNum: 1,
      pageSize: 5,
    });
    const safeJsonParse = (str) => {
      try {
        return JSON.parse(str);
      } catch (e) {
        return { content: str }; // 返回包含原始内容的对象
      }
    };

    const fieldLabels = {
      orderId: '订单编号',
      orderStatus: '订单状态',
      orderDate: '订单日期',
      businessType: '业务类型',
      customerId: '客户名称',
      paymentMethod: '付款方式',
      transportMode: '配送方式',
      logisticsNumber: '物流单号',
      consignee: '收货人',
      phone: '手机号码',
      zipcode: '邮政编码',
      streetAddress: '详细地址',
      state: '省份',
      city: '城市',
      district: '区县',
      productId: '商品编号',
      merchandiseName: '商品名称',
      merchandiseCategory: '商品类别',
      manufacturer: '生产厂商',
      productPrice: '商品价格',
      productSalesQuantity: '商品数量',
      subtotal: '小计',
      totalAmount: '总金额',
      warehouseCode: '仓库编号',
      remark: '备注'
    };

    const handlePageChange = (newPage) => {
      page.value.pageNum = newPage;
      getMessageList();
    };

    const handleSizeChange = (newSize) => {
      page.value.pageSize = newSize;
      page.value.pageNum = 1; // 切换每页大小时重置到第一页
      getMessageList();
    };

    const closeDrawer = () => {
      drawerStore.closeDrawer();
    };

    const readMessage = () => {
      // 实现一键已读逻辑
      const itemsToUpdate = obj.value.filter(item => item.readStatus === parseInt(0))

      if(itemsToUpdate.length === 0){
        return;
      }

      itemsToUpdate.forEach(item => item.readStatus = parseInt(1))

      Promise.all(itemsToUpdate.map(item =>
          updateMessage(item).then(response =>{

          }).catch(error =>{
            console.log(error)
            item.readStatus = 0;
            throw error
          })
      )).then(() =>{
        closeDrawer()
        drawerStore.setRefreshMessages(true)
      })

    };

    const handleClick = (tab) => {
      activeName.value = tab.name;
    };

    const clickMsg = (item) => {
      // 处理消息点击事件
    };

    const viewDetails = (item) => {
      // 处理查看详情事件
      item.readStatus = 1;
      updateMessage(item).then(response => {

      })
      router.push({path:'/auditManagement',})
      closeDrawer()
    };

    const getMessageList = () => {
      // 获取消息列表逻辑

      const params = {
        userId: props.userId,
        pageNum: page.value.pageNum,
        pageSize: page.value.pageSize // 使用5作为默认页大小
      };

      listMessage(params).then(response => {
        obj.value = response.rows;
        messagetotal.value = response.total;
        console.log('response',response)
        console.log('obj',obj);
      })
    };

    const isJson = (str) => {
      try {
        JSON.parse(str);
        return true;
      } catch (e) {
        return false;
      }
    };

    const getChangeDescription = (key, change) => {
      const label = fieldLabels[key] || key;
      return `${label}: 由 ${change.oldValue} 变更为 ${change.newValue}`;
    }


    watch(() => props.userId, (newUserId) => {
      if (newUserId) {
        getMessageList();
      }
    }, { immediate: true }); // 立即执行一次'

    watchEffect(() => {
      const refresh = drawerStore.refresh;
      if (refresh) {
        console.log('NdrawerStore.refresh', refresh);
        getMessageList(); // 重新获取数据
        drawerStore.setRefreshMessages(false); // 重置标志
      }
    });

    onMounted(() => {

      console.log('props.userId',props.userId)
      if(props.userId){
        getMessageList();
      }

    });

    return {
      drawer,
      activeName,
      filteredObj,
      total,
      messagetotal,
      page,
      closeDrawer,
      readMessage,
      handleClick,
      clickMsg,
      viewDetails,
      getMessageList,
      isJson,
      getChangeDescription,
      safeJsonParse,
      handleSizeChange,
      handlePageChange,

    };
  },
};
</script>


<style scoped>
/* 添加样式 */
/* 内容 */
.msgContent {
  margin-right: 5%;
  margin-top: 10px;
  font-size: 13px;
  white-space: normal; /* 允许文本换行 */
  line-height: 1.5;
  max-height: 1.5em; /* 设置最大高度为3行（每行1.5em） */
  overflow: hidden; /* 隐藏溢出内容 */
  text-overflow: ellipsis; /* 显示省略号 */
  display: -webkit-box; /* 使用弹性盒子模型 */
  -webkit-box-orient: vertical; /* 设置文本方向为垂直 */
}

/* 标题 */
.msgTitle {
  font-size: 15px;
  font-weight: bold;
  cursor: pointer;

}

/* 时间 */
.msgTime {
  font-size: 14px;
  height: 20px;
  color: #d0cbcb;
  float: right;
  margin-right: 5%;
}
.action-button {
  position: absolute;
  right: 10px;
}
.button{
  position: absolute;
  right: 40px;
  top: 80px
}
</style>
